package main

import (
	"github.com/garyburd/redigo/redis"
	"log"
	"fmt"
)

func main() {
	conn, err := redis.Dial("tcp", ":6379")
	if err != nil {
		log.Fatalf("Couldn't connect to Redis: %v\n", err)
	}
	defer conn.Close()

	//auth验证
	if _, err := conn.Do("AUTH", "root"); err != nil {
		conn.Close()

		fmt.Println( err)
	}

	stockData := map[string]map[string]string{
		"GOOG": {"company_name": "Google Inc.", "open_price": "803.99", "ask_price": "795.50", "close_price": "802.66", "bid_price": "793.36"},
		"MSFT": {"ask_price": "N/A", "open_price": "28.30", "company_name": "Microsoft Corpora", "bid_price": "28.50", "close_price": "28.37"},
	}

	// Example 1: Write command arguments out explicitly.

	for sym, row := range stockData {
		if _, err := conn.Do("HMSET", sym,
			"company_name", row["company_name"],
			"open_price", row["open_price"],
			"ask_price", row["ask_price"],
			"bid_price", row["bid_price"]); err != nil {
			log.Fatal(err)
		}
	}

	printAndDel(conn, "example 1", stockData)

	// Example 2: Construct command arguments using range over a row map.

	for sym, row := range stockData {
		args := []interface{}{sym}
		for k, v := range row {
			args = append(args, k, v)
		}
		if _, err := conn.Do("HMSET", args...); err != nil {
			log.Fatal(err)
		}
	}

	printAndDel(conn, "example 2", stockData)

	// Example 3: Construct command arguments using Redigo helper function.

	for sym, row := range stockData {
		if _, err := conn.Do("HMSET", redis.Args{sym}.AddFlat(row)...); err != nil {
			log.Fatal(err)
		}
	}

	//printAndDel(conn, "example 3", stockData)
}

func printAndDel(conn redis.Conn, message string, stockData map[string]map[string]string) {
	log.Print(message)
	for sym := range stockData {
		values, err := redis.Values(conn.Do("HGETALL", sym))
		if err != nil {
			log.Fatal(err)
		}
		log.Print(sym)
		for i := 0; i < len(values); i += 2 {
			log.Printf("  %s: %s", values[i], values[i+1])
		}
	}
	for sym := range stockData {
		if _, err := conn.Do("DEL", sym); err != nil {
			log.Fatal(err)
		}
	}
}